package com.qf.controller;

import com.github.pagehelper.PageInfo;
import com.qf.entity.Department;
import com.qf.entity.UserEmp;
import com.qf.entity.UserRole;
import com.qf.service.UserEmpService;
import com.qf.enumutil.SizeEnum;
import com.qf.enumutil.StatusEunm;
import com.qf.utils.ExcleUtil;

import com.qf.utils.NumberUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

import java.util.*;

import static com.qf.utils.NumberUtil.getNumber;

/**
 * 2019/11/20
 * 郭程鹏
 * gcp1909
 * 面向代码面向君,不负时光不负卿
 */

@Controller
public class EmpController {

    @Autowired
    private UserEmpService userEmpService;

    /**
     * 全查 分页 模糊差
     *
     * @param model
     * @param page
     * @param userName
     * @param roleName
     * @param deptName
     * @return
     */
    @RequestMapping(value = "resource/demo2/list")
    @RequiresPermissions("pre:demo2list")
    public String userEmpPage(Model model, @RequestParam(defaultValue = "1") Integer page, String userName, String roleName, String deptName) {


        Map<String, String> dimMap = new HashMap<>();
        dimMap.put("userName", userName);
        dimMap.put("roleName", roleName);
        dimMap.put("deptName", deptName);
        PageInfo<UserEmp> empPageInfo = userEmpService.UserEmpPage(page, SizeEnum.pageSize.getSize(), dimMap);
        model.addAttribute("pageInfo", empPageInfo);
        model.addAttribute("userName", userName);
        model.addAttribute("roleName", roleName);
        model.addAttribute("deptName", deptName);

        return "resource/demo2/list";
    }

    /**
     * 修改的二级联动前置查询
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("resource/demo2/preUpdate")
    @RequiresPermissions("pre:preUpdate")
    public String getAllDeptName(Model model, @RequestParam("empId") Integer id) {

        List<Department> deptName = userEmpService.allDeptName();

        UserEmp userEmp = userEmpService.preUserEmp(id);

        List<UserRole> userRoles = userEmpService.preUserRole(userEmp.getDeptId());


        model.addAttribute("deptName", deptName);
        model.addAttribute("userEmp", userEmp);
        model.addAttribute("userRoles", userRoles);

        return "resource/demo2/update";
    }

    /**
     * ajax二级联动
     *
     * @param deptId
     * @return List<UserRole>
     */
    @RequestMapping("resource/demo2/ajaxRequest")
    @RequiresPermissions("pre:ajaxRequest")
    @ResponseBody
    public List<UserRole> ajaxRequest(@RequestParam("deptId") Integer deptId) {
        List<UserRole> roleList = userEmpService.preUserRole(deptId);
        return roleList;
    }

    /**
     * 修改员工信息
     * 注解执行 声明式事务
     *
     * @param userEmp
     * @param response
     */
    @RequestMapping("resource/demo2/updateUserEmp")
    @RequiresPermissions("pre:updateUserEmp")
    @Transactional
    public void updateUserEmp(UserEmp userEmp, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //执行修改
        userEmpService.updateEmp(userEmp);
        try {
            response.getWriter().print("<script>alert('修改成功');location.href='/resource/demo2/list'</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 添加用户前置信息回显，生成编号和账号
     *
     * @param model
     * @return
     */
    @RequestMapping("resource/demo2/addEmpPre")
    @RequiresPermissions("pre:addEmpPre")
    public String addEmpPre(Model model) {
        List<Department> deptName = userEmpService.allDeptName();
        //员工的编号
        String userId = getNumber(4);
        //员工的登陆账号
        String loginNumber = getNumber(10);
        model.addAttribute("deptName", deptName);
        model.addAttribute("userId", userId);
        model.addAttribute("loginNumber", loginNumber);
        return "resource/demo2/add";
    }

    /**
     * /生成指定位数的随机数
     *
     * @param length
     * @return
     */


    /**
     * 异步校验用户名是否可用
     *
     * @param userName
     * @return
     */
    @ResponseBody
    @RequestMapping("resource/demo2/checkName")
    @RequiresPermissions("pre:checkName")
    public String ajaxCheckName(@RequestParam("userName") String userName) {

        Integer resout = userEmpService.checkUserName(userName);
        if (resout > 0) {
            return "1";
        }
        return "0";
    }

    /**
     * 添加用户
     *
     * @param userEmp
     * @param response
     */
    @Transactional
    @RequestMapping("resource/demo2/insertUser")
    @RequiresPermissions("pre:insertUser")
    public void insertUserEmp(UserEmp userEmp, HttpServletResponse response) {
        int emp = userEmpService.addUserEmp(userEmp);
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        try {
            if (emp > 0) {
                response.getWriter().print("<script>alert('添加成功');location.href='/resource/demo2/list'</script>");
            } else {
                response.getWriter().print("<script>alert('添加成功');location.href='/resource/demo2/list'</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据id查看员工信息
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/resource/demo2/view")
    @RequiresPermissions("pre:view")
    public String userView(@RequestParam("empId") Integer id, Model model) {
        UserEmp userEmp = userEmpService.viewUserEmp(id);
        model.addAttribute("userEmp", userEmp);
        return "/resource/demo2/view";
    }


    /**
     * 根据主键Id删除信息
     *
     * @param id
     * @param response
     */
    @RequestMapping("/resource/demo2/deleteEmp")
    @RequiresPermissions("pre:deleteEmp")
    public void deleteUserEmpById(@RequestParam("empId") Integer id, HttpServletResponse response) {
        //将对象设置位离职
        int i = userEmpService.deleteUserEmpById(id, StatusEunm.OUTlINE.getStatus());
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        try {
            if (i > 0) {
                response.getWriter().print("<script>alert('删除成功!');location.href='/resource/demo2/list'</script>");
            } else {
                response.getWriter().print("<script>alert('删除失败!');location.href='/resource/demo2/list'</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //批量删除 导出excle表格
    @RequestMapping("/resource/demo2/doAction")
    @RequiresPermissions("pre:doAction")
    public void deleteMany(@RequestParam("empId") List<Integer> empId, @RequestParam("method") String method, HttpServletResponse response) {
        System.out.println("数据：" + empId);
            //method=deleteAll 批量删除
            if (method.equals("deleteAll")) {

                int i = userEmpService.deleteUserEmpMany(empId, StatusEunm.OUTlINE.getStatus());
                try {
                    if (i > 0) {
                        response.getWriter().print("<script>alert('删除成功!');location.href='/resource/demo2/list'</script>");
                    } else {
                        response.getWriter().print("<script>alert('删除失败!');location.href='/resource/demo2/list'</script>");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (method.equals("doExcle")) {

                //method=checkOut 导出数据
                List<UserEmp> userEmps = userEmpService.userList(empId);
                for (UserEmp emp : userEmps) {
                    System.out.println(emp.getUserName());
                }

                String number = getNumber(6);


                response.setContentType("application/x-download");

                String excleName = "excle_"+number+ ".xls";
                response.addHeader("Content-Disposition", "attachment;filename=" + excleName);
                //设置表名
                ExcleUtil.createFirstRow("用户信息");
                //设置内容
                ExcleUtil.createSheetValue(userEmps);
                try {

                    ExcleUtil.export(response.getOutputStream());

                    try {
                        response.getWriter().print("<script>alert('导出成功!');location.href='/resource/demo2/list'</script>");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    try {
                        response.getWriter().print("<script>alert('导出失败!');location.href='/resource/demo2/list'</script>");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }

            }


    }
}